package com.example.multiReactorMultiThread;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MainReactor implements Runnable{

    private int port;
    private Selector selector;
    private int subReactorNums;

    public MainReactor(int port,int subReactorNums){
        this.subReactorNums = subReactorNums;
        this.port=port;
        init();
    }
    private void init() {
        try {
            selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT,new Acceptor(selector,serverSocketChannel,subReactorNums));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    process(selectionKey);
                    iterator.remove();
                }
            }catch (Exception e){

            }
        }
    }

    private void process(SelectionKey selectionKey){
        Runnable runnable = (Runnable)selectionKey.attachment();
        runnable.run();
    }
}
